import {
  Button,
  Card,
  Col,
  Drawer,
  Flex,
  Form,
  Input,
  message,
  Row,
  Space,
  Table,
} from "antd";
import { useDispatch, useSelector } from "react-redux";
import {
  addCategory,
  deleteCategory,
  ICategory,
  selectAllCategory,
  updateCategory,
} from "../../../store/slices/productsSlice.ts";
import { useState } from "react";

export default function InventoryCategory() {
  const [messageApi, contextHolder] = message.useMessage();
  const dispatch = useDispatch();

  const categories = useSelector(selectAllCategory);

  const [openEditCategoryDrawer, setOpenEditCategoryDrawer] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [crtCategory, setCrtCategory] = useState<ICategory>({
    id: -1,
    cName: "",
    note: "",
    createTime: "",
  });

  const openEditDrawer = (c: ICategory | null) => {
    if (c) {
      setCrtCategory(c);
      setEditMode(true);
    } else {
      setCrtCategory({ id: -1, cName: "", note: "", createTime: "" });
    }
    setOpenEditCategoryDrawer(true);
  };

  const closeEditDrawer = () => {
    setOpenEditCategoryDrawer(false);
    setEditMode(false);
  };

  const DrawerExtra = () => {
    if (editMode) {
      return (
        <Space>
          <Button
            type="primary"
            onClick={() => {
              dispatch(updateCategory(crtCategory));
              closeEditDrawer();
              messageApi.success(`修改${crtCategory.cName}信息成功`);
            }}>
            修改
          </Button>
          <Button onClick={closeEditDrawer}>取消</Button>
        </Space>
      );
    } else {
      return (
        <Space>
          <Button
            type="primary"
            onClick={() => {
              dispatch(
                addCategory({
                  ...crtCategory,
                  id: Math.floor(Math.random() * 1000),
                }),
              );
              closeEditDrawer();
              messageApi.success(`新增${crtCategory.cName}信息成功`);
            }}>
            新增
          </Button>
          <Button onClick={closeEditDrawer}>取消</Button>
        </Space>
      );
    }
  };

  return (
    <>
      <Flex vertical style={{ height: "100%", padding: "10px" }}>
        <Card
          title="商品分类列表"
          extra={
            <Button type="primary" onClick={() => openEditDrawer(null)}>
              新建分类
            </Button>
          }>
          <Table dataSource={categories} rowKey="id">
            <Table.Column title="编号" dataIndex="id" />
            <Table.Column title="分类名" dataIndex="cName" />
            <Table.Column title="备注" dataIndex="note" />
            <Table.Column title="创建时间" dataIndex="createTime" />
            <Table.Column
              title="操作"
              render={(_value, record: ICategory) => (
                <Space>
                  <a onClick={() => openEditDrawer(record)}>编辑</a>
                  <a
                    onClick={() => {
                      dispatch(deleteCategory(record));
                      messageApi.success(`成功删除${record.cName}`);
                    }}>
                    删除
                  </a>
                </Space>
              )}
            />
          </Table>
        </Card>
      </Flex>
      <Drawer
        title={editMode ? "编辑分类" : "新增分类"}
        closeIcon={null}
        open={openEditCategoryDrawer}
        size="large"
        onClose={closeEditDrawer}
        extra={<DrawerExtra />}>
        <Form>
          <Row>
            <Col span={12}>
              <Form.Item label="分类名">
                <Input
                  value={crtCategory.cName}
                  onChange={(e) =>
                    setCrtCategory({ ...crtCategory, cName: e.target.value })
                  }
                />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item label="备注">
                <Input.TextArea
                  autoSize={true}
                  count={{ max: 300 }}
                  showCount={true}
                  style={{ resize: "none" }}
                  value={crtCategory.note}
                  onChange={(e) =>
                    setCrtCategory({ ...crtCategory, note: e.target.value })
                  }
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Drawer>
      {contextHolder}
    </>
  );
}
